<template>
	<div class="tui-conversation" @click="handleClickConv" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
			
			<TUIContact></TUIContact>
			
			
			<div class="tui-search-more">
				<ul class="tui-search-more-list">
					<li class="list-item" @click="notify('system')" style="position: relative;">
						<div class="list-item-title" style="text-align: right;">
							<text :class="lang!='ru'?'font28':'font20'" style="text-align: right;">{{ system_btn }}</text>
						</div>
						<view class="right_title" v-if="systemMessageCount > 0 "
							style="position: absolute;left: 85%;top: -60%;">
							<view class="text2">{{ systemMessageCount }}</view>
						</view>
					</li>
					<li class="list-item" @click="notify('transaction')" style="position: relative;">
						<div class="list-item-title" style="text-align: right;">
							<text :class="lang!='ru'?'font28':'font20'" style="text-align: right;">{{ order_btn }}</text>
						</div>
						<view class="right_title" v-if="otherMessageCount > 0"
							style="position: absolute;left: 85%;top: -60%;">
							<view class="text3">{{ otherMessageCount>99?'99+':otherMessageCount }}</view>
						</view>
					</li>
				</ul>
			</div>
			
			
			<view v-if="is_master==1">
				<TUISearch searchType="global" />
				<ConversationHeader v-if="isShowConversationHeader" ref="headerRef" />
			</view>
			
			
			<ConversationNetwork />
			<ConversationList class="tui-conversation-list" ref="conversationListDomRef"
				@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef"
				v-if="mobile=='23010310000'||mobile=='23010310001'||mobile=='23010310002'||mobile=='23010310003'||mobile=='23010310004'||mobile=='23010310005'||mobile=='23010310006'
				||mobile=='23010310007'||mobile=='23010310008'||mobile=='23010310009'||mobile=='23010310010'||mobile=='23010310011'||mobile=='23010310012'||mobile=='23010310013'" />
			<ConversationList1 class="tui-conversation-list" ref="conversationListDomRef"
				@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef" v-else />
			<vipPopup v-if="vipShow" :show="vipShow" />
			
			
			<!-- v-if="plat=='app'&&tan_flag==true&&permissionsShow==true" -->
			<!-- <view
				style="width: 100%;height: 100%;background-color: #000000; opacity: 0.8; z-index: 999;position: fixed; top: 0%; left: 0%;">
			</view> -->
			 
			<permissionChat ref="permissionChat" v-show="plat=='app'&&tan_flag==true&&permissionsShow==true">
					<!-- <div>{{plat}}</div>
				<div>{{lang}}</div>
				<div>{{tan_flag}}</div>
				<div>{{permissionsShow}}</div>
				{{plat=='app'&&lang=='zh'&&tan_flag==true&&permissionsShow==true}} -->
			</permissionChat>
			
			<!-- v-if="plat=='app'&&lang=='zh'&&tan_flag==true&&permissionsShow==true" -->
			<!-- v-if="plat=='app'&&lang=='ru'&&tan_flag==true&&permissionsShow==true" -->
			
			
			<!-- <view v-if="plat=='app'&&lang=='zh'&&tan_flag==true&&permissionsShow==true" @click="install_cation()"
				style="width: 100%;height: 300px;position: fixed; bottom: 0%; left: 0%;z-index: 1000;">
				<image style="width: 100%;height:100%" src="https://app.gluz.com.cn/uniappAssets/static/images/tan_zh.png">
				</image>
			</view>
			<view @click="install_cation()" v-if="plat=='app'&&lang=='ru'&&tan_flag==true&&permissionsShow==true"
				style="width: 100%;height: 300px;position: fixed; bottom: 0%; left: 0%;z-index: 1000;">
				<image style="width: 100%;height:100%" src="https://app.gluz.com.cn/uniappAssets/static/images/tan_ru.png">
				</image>
			</view> -->
			
		
		
	</div>
</template>


<script lang="ts">
	import permissionChat from "@/components/permissionChat.vue";
	export default {
		components: {
			permissionChat
		},
		data() {
			return {
				iskf: null,
				to_mobile: null,
				type: null,
				vipShow: false,
				is_master: 0,
				systemMessageCount: 0,
				otherMessageCount: 0,
				lang: 'zh',
				system_btn: '系统通知',
				order_btn: '交易通知',
				plat: 'app',
				tan_flag: false,
				permissionsShow: false,
				
				
			}
		},
		onLoad(payload : any) {
			const that = this
			that.iskf = payload.iskf
			that.to_mobile = payload.to_mobile
			that.type = payload.type
		},

		onShow() {
			const that = this
			const systemInfo = uni.getSystemInfoSync();
			const platform = systemInfo.platform;
			that.plat = uni.getStorageSync('plat')
			
			that.lang = uni.getStorageSync('lang')
			
			that.permissionsShow = uni.getStorageSync('permissionsShow');
			
			if (uni.getStorageSync('userInfoFull')) {
				that.is_master = uni.getStorageSync('userInfoFull').user.is_master
			}
			
			if (that.lang == 'zh') {
				that.system_btn = '系统通知'
				that.order_btn = '交易通知'
			} else {
				that.system_btn = 'Системное уведомление'
				that.order_btn = 'Уведомление о сделке'
			}
			
			if (that.plat == 'app') {
				if (this.$refs.permissionChat) {
					this.$refs.permissionChat.checkRecordPermission()
					this.$refs.permissionChat.checkNoticePermission()
					this.$refs.permissionChat.checkWindowPermission()
				}

				setTimeout(function () {
					console.log("-------------------------------------")
					console.log(uni.getStorageSync('message_permission'))
					console.log(uni.getStorageSync('record_permission'))
					console.log(uni.getStorageSync('xuanfuchuang_permission'))
					console.log("-------------------------------------")
				
					if (platform != 'ios') {
						if ((uni.getStorageSync('message_permission') == 1) && (uni.getStorageSync('record_permission') == 1) && (uni.getStorageSync('xuanfuchuang_permission') == 1)) {
							that.tan_flag = false
						} else {
							that.tan_flag = true
						}
					} else {
						if ((uni.getStorageSync('message_permission') == 1) && (uni.getStorageSync('record_permission') == 1)) {
							that.tan_flag = false
						} else {
							that.tan_flag = true
						}
					}

					uni.setNavigationBarTitle({
						title: '     '
					})
				}, 2000)
			}
			
			uni.request({
				url: 'https://app.gluz.com.cn/api/basic/getNoticeNum',
				data: { mobile: uni.getStorageSync('mobile') },
				header: {
					xzdToken: uni.getStorageSync("xzdToken")
				},
				success: (r) => {
					this.otherMessageCount = Number(r.data.data.other)
					this.systemMessageCount = Number(r.data.data.system)
				},
			})

			//this.$store.state.c2cMessageCount
		}

	}
</script>
<script lang="ts" setup>
	import chatInterceptor from "@/common/chatInterceptor"
	import { visitChat } from "@/common/public"
	import {
		HTTP_REQUEST_URL,
		PERFIX,
		kfs,
		IM_SDKAppID
	} from '@/config/app';
	import TencentCloudChat from '@tencentcloud/chat';
	import { TUIStore, StoreName, TUIConversationService } from "@tencentcloud/chat-uikit-engine";
	import { ref, onMounted, reactive, onBeforeMount, getCurrentInstance, computed } from "../../adapter-vue";
	import { TUIGlobal } from "../../utils/universal-api/index";
	import TUIContact from "../TUIContact/index";
	import ConversationList from "./conversation-list/index.vue";
	import ConversationList1 from "./conversation-list/indexlist.vue";
	import TUISearch from '../TUISearch/index.vue';
	import ConversationHeader from "./conversation-header/index.vue";
	import ConversationNetwork from "./conversation-network/index.vue";
	import { onHide } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
	import store from "@/store/index.js";
	// #ifdef MP-WEIXIN
	import "./subPackage-init.ts";
	// #endif

	const emits = defineEmits(["handleSwitchConversation"]);
	const totalUnreadCount = ref(0);
	const headerRef = ref<HTMLElement | undefined>();
	const conversationListDomRef = ref<HTMLElement | undefined>();
	const touchX = ref<number>(0);
	const touchY = ref<number>(0);
	const isShowConversationHeader = ref<boolean>(true);

	const mobile = uni.getStorageSync('mobile');
	const chat = computed(() => { return store.state.im.chat });
	const getCurrent = getCurrentInstance();
	
	

	// #ifdef MP
	onMounted(() => {
		let isReady = chat.value.isReady();
		if (isReady) {
			toDetail();
		}
		chat.value.on(TencentCloudChat.EVENT.SDK_READY, function () {
			toDetail();
		});
	})
	// #endif
	if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
		|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
		let chat1 = TencentCloudChat.create({
			SDKAppID: 1400818966 // Replace `0` with the `SDKAppID` of your Chat app during access.
		});
		let promise = chat1.logout();
		promise.then(function (imResponse) {
			console.log(imResponse.data); // 登出成功
		}).catch(function (imError) {
			console.warn('logout error:', imError);
		});
	}

	const toDetail = () => {
		const params = getCurrent.data;
		if (!params.to_mobile) {
			return
		}
		// 聊天的userID
		const userID = params.iskf === 'true' ? kfs[0] : PERFIX + params.to_mobile;
		const conversationID = `C2C${userID}`;
		TUIConversationService.getConversationProfile(conversationID)
			.then((res) => {
				console.log('createC2CConversation-success', res)
				TUIConversationService.switchConversation(
					res.data.conversation.conversationID
				);
				uni.navigateTo({
					url: '/TUIKit/components/TUIChat/index'
				});
			})
			.catch((err) => {
				// uni.showToast({
				// 	title: "The other party has not registered for a chat service",
				// 	icon: 'none'
				// })
				console.warn("打开会话失败", err.code, err.msg);

				const userID2 = kfs[0];
				const conversationID2 = `C2C${userID2}`;
				TUIConversationService.getConversationProfile(conversationID2)
					.then((res) => {
						console.log('createC2CConversation-success', res)
						TUIConversationService.switchConversation(
							res.data.conversation.conversationID
						);
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					}).catch((err) => {
						console.warn("打开会话失败", err.code, err.msg);
					});
			});
	}
	TUIStore.watch(StoreName.CONV, {
		totalUnreadCount: (count : number) => {
			totalUnreadCount.value = count;
		},
	});

	TUIStore.watch(StoreName.CUSTOM, {
		isShowConversationHeader: (showStatus : boolean) => {
			isShowConversationHeader.value = showStatus !== false;
		},
	});


	const handleSwitchConversation = async (conversationID : string) => {

		// console.log("getCurrent",getCurrent);
		// 即时聊天权限与业务控制
		const interceptorRes = await chatInterceptor(getCurrent);
		// console.log("chatInterceptor",chatInterceptor);
		if (!interceptorRes) return;


		tj(conversationID)
		let lang = getApp().globalData.lang;
		if (lang == 'ru') {
			tj(conversationID)
			return;
		}

		uni.request({
			url: HTTP_REQUEST_URL + '/demo/mine',
			data: { mobile: mobile },
			header: {},
			success: (res) => {
				if (res) {
					if (res.data) {
						if (res.data.data) {
							if (res.data.data.level == 0) {

								uni.request({
									url: HTTP_REQUEST_URL + '/demo/message_score',
									data: { mobile: mobile },
									header: {},
									success: (r) => {
										if (r.data.data) {
											tj(conversationID)
										} else {
											uni.showModal({
												content: '您的权限不足哦!请联系工作人员!',
												showCancel: false,
												confirmText: '是',
											})
											return false;

										}
									},
								})

							} else {
								tj(conversationID)
							}
						}
					}
				}
			}
		})

	};


	const closeChildren = () => {
		headerRef?.value?.closeChildren();
		conversationListDomRef?.value?.closeChildren();
	};

	const handleClickConv = () => {
		closeChildren();
	};

	onHide(closeChildren);

	const handleTouchStart = (e : any) => {
		touchX.value = e.changedTouches[0].clientX;
		touchY.value = e.changedTouches[0].clientY;
	};

	const handleTouchEnd = (e : any) => {
		let x = e.changedTouches[0].clientX;
		let y = e.changedTouches[0].clientY;
		let turn = "";
		if (x - touchX.value > 50 && Math.abs(y - touchY.value) < 50) {
			//右滑
			turn = "right";
		} else if (x - touchX.value < -50 && Math.abs(y - touchY.value) < 50) {
			//左滑
			turn = "left";
		}
		if (y - touchY.value > 50 && Math.abs(x - touchX.value) < 50) {
			//下滑
			turn = "down";
		} else if (y - touchY.value < -50 && Math.abs(x - touchX.value) < 50) {
			//上滑
			turn = "up";
		}
		//根据方向进行操作
		if (turn === "down" || turn === "up") {
			closeChildren();
		}
	};

	const getPassingRef = (ref) => {
		ref.value = conversationListDomRef.value;
	}
	

	const tj = (conversationID) => {
		if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
			|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
			let fruits = conversationID.split("C2Cgluz_");
			setTimeout(() => {
				// 使用uni.navigateTo进行页面跳转
				TUIGlobal?.navigateTo({
					url: "/TUIKit/components/TUIConversation/indexlist?mobile=" + fruits[1],
				});
			}, 1000); // 延迟5秒
		} else {
			setTimeout(() => {
				// 使用uni.navigateTo进行页面跳转
				TUIGlobal?.navigateTo({
					url: "/TUIKit/components/TUIChat/index",
				});
			}, 1000); // 延迟5秒
		}

		emits("handleSwitchConversation", conversationID);
	};

	const install_cation = () => {
		uni.navigateTo({
			url: `/pages/user/install/install`
		})
	};


	const notify = (type) => {
		const typeObj = {
			transaction: "transactionNotice",
			system: "systemNotification",
			individual: "individual"
		}
		//类型（系统通知，交易通知，个人通知）
		uni.navigateTo({
			url: `/pages/message/${typeObj[type]}/${typeObj[type]}`
		})
	};
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
	.tui-conversation {
		height: auto !important;
	}

	.toggle {
		width: 28px;
		height: 28px;
		background-color: #ddd;
	}

	.tui-search-more {
		width: 100%;

		.more {}

		&-list {
			display: flex;
			margin: 10px 0px;
			list-style: none;
			cursor: pointer;
			z-index: 1000;
			background: #ffffff;
			display: flex;
			padding: 0px;
			width: 100%;
			box-sizing: border-box;

			.list-item {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				height: 40px;
				padding: 0 10px;
				border: 1rpx solid #ddd;
				flex: 1;
				margin: 0 30rpx;
				border-radius: 10rpx;

				&-icon {
					margin-right: 2px;
				}

				&-title {
					font-size: 14px;
					text-wrap: nowrap;
				}
			}
		}
	}

	.text3 {
		height: 60.12rpx;
		min-width: 60.12rpx;
		padding: 0 10rpx;
		background-color: #ED793C;
		color: #FFFFFF;
		border-radius: 30.06rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10rpx;
	}

	.right_title {
		display: flex;
		flex-direction: row;
		align-items: flex-end;
		justify-content: flex-end;
		flex-direction: column;

		.text1 {
			font-size: 29rpx;
			font-weight: 300;
			color: #454545;
			line-height: 30rpx;
			margin-bottom: 10rpx;
		}

		.text2 {
			height: 60.12rpx;
			width: 60.12rpx;
			background-color: #ED793C;
			color: #FFFFFF;
			border-radius: 30.06rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 10rpx;
		}
	}

	.font28 {
		font-size: 28rpx;
	}

	.font20 {
		font-size: 20rpx;
	}
</style>